package app.fugema.shop.main.setting.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.base.common.app.LoginUtils;
import com.base.common.utils.LogUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.base.BaseTitleActivity;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;
import app.fugema.shop.R;
import app.fugema.shop.databinding.ActivityWebBinding;
import app.fugema.shop.main.goods.view.GoodsDetailActivity;
import app.fugema.shop.main.setting.vm.SettingUserVM;

import androidx.core.content.ContextCompat;

/**
 * 网页
 */
public class WebActivity extends BaseTitleActivity<ActivityWebBinding, SettingUserVM>
{
    private static String WEB_URL= "webUrl";
    private String mUrl;
    private AgentWeb agentWebView;
    public static void start(Context context,String url )
    {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra(WEB_URL,url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
    }

    @Override
    protected void initView()
    {
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("网页",R.color.white);
    }

    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }

    @SuppressLint("JavascriptInterface")
    @Override
    protected void initData()
    {
        mUrl = getIntent().getStringExtra(WEB_URL);
        if( UIUtils.isNotEmpty( mUrl ) )
        {
            ///m-wap/signin/?token=ZitrKzZYWGV6dDNrOXNIVmpVZmpIVmp2dC9KRnplS1oxdEJXTzQwVTR5UlhqVWp3Tmt6cTdLS0JMcGNwUjFqdkFkY2J6ZExtRnJ1Qi9JSXB4OHpOd2c9PQ==
            LogUtil.e("URL = "+mUrl);
            agentWebView = AgentWeb.with( this )
                    .setAgentWebParent(binding.webContent,new LinearLayout.LayoutParams(-1,-1))
                    .useDefaultIndicator(ContextCompat.getColor( this,android.R.color.holo_green_light ))
                    .setWebChromeClient( new MyWebChromeClient() )
                    .setWebViewClient( new MyWebViewClient() )
                    .setSecurityType(AgentWeb.SecurityType.DEFAULT_CHECK)
                    .createAgentWeb()
                    .ready()
                    .go(mUrl);

            //清缓存和记录
            agentWebView.getWebCreator().getWebView().clearCache(true);
            agentWebView.getWebCreator().getWebView().clearHistory();
            agentWebView.getWebCreator().getWebView().requestFocus();

            WebSettings webSettings = agentWebView.getWebCreator().getWebView().getSettings();
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            //        打开页面时， 自适应屏幕：
            //设置此属性，可任意比例缩放 将图片调整到适合webview的大小
            webSettings.setUseWideViewPort(true);
            // 缩放至屏幕的大小
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setSupportZoom(true);
            //支持自动加载图片
            webSettings.setLoadsImagesAutomatically(true);
            webSettings.setAllowFileAccess(true);
            webSettings.setDatabaseEnabled(true);
            //不设置此 无法加载h5
            webSettings.setDomStorageEnabled(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);  //支持js调用window.open方法
            webSettings.setJavaScriptEnabled(true);



            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            {
                webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (agentWebView.handleKeyEvent(keyCode, event))
        {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onPause() {
        super.onPause();
        agentWebView.getWebLifeCycle().onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        agentWebView.getWebLifeCycle().onResume();
    }


    @Override
    protected void onDestroy() {
        agentWebView.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }


    public class MyWebChromeClient extends WebChromeClient
    {
        @Override
        public void onReceivedTitle(WebView view, String title)
        {
            super.onReceivedTitle(view, title);
            setTitle(title);
        }
    }

    public class MyWebViewClient extends WebViewClient
    {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
        {
            Uri url = request.getUrl();
            // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不另跳浏览器
            // 在2.3上面不加这句话，可以加载出页面，在4.0上面必须要加入，不然出现白屏

            if (url.toString().contains("?") )
            {
                //跳转的链接 待 ? 参数
                //http://ctrip.hbhnt.net/h5/pages/goods/detail/detail?sku_id=18
                //http://ctriph5.hbhnt.net/#/pages/goods/goods?type=goods&id=25&sku_id=25
                //goods?type=goods&id=170&sku_id=170
                String tempVrUrl = "sku_id=";

                if( !url.toString().contains("token") )
                {
                    StringBuffer tokensb = new StringBuffer();
                    if(LoginUtils.isLogin() && UIUtils.isNotEmpty( LoginUtils.getToken() ))
                    {

                        tokensb.append("&");
                        tokensb.append("token");
                        tokensb.append("=");
                        tokensb.append(LoginUtils.getToken());
                    }
                    /*
                    if( url.toString().contains(tempVrUrl) )
                    {
                        // url 包含 sku_id 取出 skuid 跳转 到 商品详
                        int indexW =  url.toString().lastIndexOf("?");
                        String paramStr = url.toString().substring( indexW+1 );
                        //type=goods&id=25&sku_id=25
                    }
                    else{}
                    */
                    view.loadUrl(url.toString() + tokensb.toString());
                    return true;
                    //agentWebView.getWebCreator().getWebView().stopLoading();
                    //return false;
                }
                else
                {
                    view.loadUrl(url.toString());
                    return true;
                }
            }
            else
            {
                if(LoginUtils.isLogin() && UIUtils.isNotEmpty( LoginUtils.getToken() ))
                {
                    StringBuffer tokensb = new StringBuffer();
                    tokensb.append("?");
                    tokensb.append("token");
                    tokensb.append("=");
                    tokensb.append(LoginUtils.getToken());

                    view.loadUrl(url.toString() + tokensb.toString());

                    return true;
                }

            }


            //处理http和https开头的url
            //view.loadUrl(url);
            // true

            return false;
        }


        @Override
        public void onPageFinished(WebView view, String url)
        {
            //setToolbarTitle(viewDataBinding.includeTitle.toolbar,view.getTitle());
            //setToolBar(viewDataBinding.includeTitle.toolbar);
            // 网页加载完成 后
            // addOnClickListner(view);
        }
    }

}
